package ve.lm.hrms_cy.Service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ve.lm.hrms_cy.Entity.Response.ResponseEntityCY;
import ve.lm.hrms_cy.Entity.User;
import ve.lm.hrms_cy.Mapper.UserMapper;
import ve.lm.hrms_cy.Utils.JwtUtil;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserMapper userMapper;




    private String generateToken(Long id ,String username ,String permission){

        return jwtUtil.generateToken(id,username,permission);

    }

//    /**
//     * 通过用户名或邮箱验证用户身份并生成 JWT Token
//     * @param usernameOrEmail 用户名或邮箱
//     * @param password 用户密码
//     * @return 生成的 JWT Token
//     */
//    public String authenticateUser(String usernameOrEmail, String password) {
//        // 查询数据库中的用户，支持根据用户名或邮箱查询
//        User user = userMapper.selectOne(new QueryWrapper<User>()
//                .eq("name", usernameOrEmail)
//                .or()
//                .eq("email", usernameOrEmail));
//
//        // 用户不存在或密码不匹配，抛出异常
//        if (user == null) {
//            throw new RuntimeException("用户不存在");
//        }
//
//        if (!password.equals(user.getPassword())) {
//            throw new RuntimeException("密码错误");
//        }
//        // 用户认证通过，生成 JWT Token
//        return jwtUtil.generateToken(user.getId(), user.getName() ,user.getPermission());
//    }

    public String userLogin(String userNameOrEmail ,String password){

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPassword , password).and(w->w.eq(User::getName , userNameOrEmail).or().eq(User::getEmail ,userNameOrEmail));

        User findUser=userMapper.selectOne(lambdaQueryWrapper);

        if(findUser!=null){

           return generateToken(findUser.getId() ,findUser.getName() ,findUser.getPermission());

        }

        return null;

    }

    public String userLoginForPermission(String userNameOrEmail ,String password){

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPassword , password).and(w->w.eq(User::getName , userNameOrEmail).or().eq(User::getEmail ,userNameOrEmail));

        User findUser=userMapper.selectOne(lambdaQueryWrapper);

        if(findUser!=null){


            return findUser.getPermission();

        }

        return null;

    }

    public Long userLoginForId(String userNameOrEmail ,String password){

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPassword , password).and(w->w.eq(User::getName , userNameOrEmail).or().eq(User::getEmail ,userNameOrEmail));

        User findUser=userMapper.selectOne(lambdaQueryWrapper);

        if(findUser!=null){


            return findUser.getId();

        }

        return null;

    }

    @Transactional
    public ResponseEntityCY<Boolean> registerUser(User userRequest) {
        String name = userRequest.getName();
        String email = userRequest.getEmail();

        // 1. 查询 name 或 email 冲突，且状态不是“注销”
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper ->
                wrapper.eq(User::getName, name)
                        .or()
                        .eq(User::getEmail, email)
        ).ne(User::getStatus, "注销");

        List<User> existing = userMapper.selectList(queryWrapper);
        if (!existing.isEmpty()) {
            return new ResponseEntityCY<>("409", false, false, "用户名或邮箱已存在，且未注销！");
        }

        // 2. 获取当前最大 ID（可能为空）
        Long maxId = Optional.ofNullable(
                userMapper.selectList(null)
                        .stream()
                        .map(User::getId)
                        .max(Long::compareTo)
                        .orElse(0L)
        ).orElse(0L);

        Long newId = maxId + 1;

        // 3. 构造新用户对象（包括 registerTime）
        User newUser = new User(
                userRequest.getName(),
                userRequest.getEmail(),
                userRequest.getPermission(),
                userRequest.getStatus(),
                userRequest.getPassword()
        );
        newUser.setId(newId);
        newUser.setRegisterTime(LocalDateTime.now());

        // 4. 添加进数据库
        int rows = userMapper.insert(newUser);
        if (rows > 0) {
            return new ResponseEntityCY<>("200", true, true, "用户添加成功！");
        } else {
            return new ResponseEntityCY<>("500", false, false, "添加用户失败！");
        }
    }





}


